import 'dart:io';

import 'package:FineArt/constants.dart';
import 'package:FineArt/core/api/class_api.dart';
import 'package:FineArt/core/api/module_api.dart';
import 'package:FineArt/core/api/resource_api.dart';
import 'package:FineArt/core/model/class_entity.dart';
import 'package:FineArt/core/model/student_entity.dart';
import 'package:FineArt/core/utils/toast.dart';
import 'package:FineArt/core/widget/grid/list_item_video_play.dart';
import 'package:FineArt/page/imageview/FavoritorChooseFolder.dart';
import 'package:FineArt/page/imageview/LargePhotoView.dart';
import 'package:FineArt/utils/log_util.dart';
import 'package:FineArt/utils/platform_util.dart';
import 'package:FineArt/utils/size_config.dart';
import 'package:FineArt/utils/sputils.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:fijkplayer/fijkplayer.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_easyrefresh/material_footer.dart';
import 'package:flutter_swiper/flutter_swiper.dart';

import 'package:extended_image/extended_image.dart';
import 'TeacherCourseView.dart';
import 'RoundCheckBox.dart';

class VideoPlayer extends StatefulWidget {
  // ignore: non_constant_identifier_names
  static void JumpToVideoView(Resource resource, context) {
    Navigator.of(context).push(MaterialPageRoute(builder: (context) {
      return VideoPlayer(
        resource:resource,
      );
    }));
  }

  Resource resource;

  VideoPlayer({this.resource});

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return new _VideoPlayerState();
  }
}

class _VideoPlayerState extends State<VideoPlayer> {
  var width;
  List<ClassEntity> clList = new List();
  List<StudentEntity> stuList = new List();

  String largeImageUrl = "";
  Map video_info_map = new Map();
  ResourceInfoVideo curVideo;

  Map class_student_map = new Map(); //班级-学生的map

  List<Resource> resources = new List();

  Resource currentResource;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getClasses();
    currentResource = widget.resource;
    getResourceDetail();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
  }

  void getResourceDetail() {
    ResourceApi().resourceDetail(widget.resource.id, widget.resource.type).then((res) {
      if (res.code == 200) {
        if (res.data.type == 2) //视频
        {
          ResourceInfoVideo info = res.data.info;
          video_info_map[widget.resource.id] = info;
          String url = info.url;
          setState(() {
            _getRelatedResources(info.path,info.albumname);
            curVideo = info;
            if (defaultUrl != info.url) {
              defaultUrl = url;
              configPlayer();
            }
          });
        }
      }
    });
  }


  void getVideoDetail(Resource resource) {
    if (video_info_map[resource.id] != null) {
      ResourceInfoVideo info = video_info_map[resource.id];
      LogUtil.d("video_info_map[idx]!=null url ${info.url}");
      setState(() {
        currentResource = resource;
        if (defaultUrl != info.url) {
          defaultUrl = info.url;
          curVideo = info;
          configPlayer();
        }
      });

      return;
    }
    ResourceApi()
        .resourceDetail(resource.id, resource.type)
        .then((res) {
      if (res.code == 200) {
        if (res.data.type == 2) //视频
            {
          ResourceInfoVideo info = res.data.info;
          video_info_map[resource.id] = info;
          String url = info.url;
          setState(() {
            currentResource = resource;
            curVideo = info;
            if (defaultUrl != info.url) {
              defaultUrl = url;
              LogUtil.d("resourceDetail url $defaultUrl");
              configPlayer();
            }
          });
        }
      }
    });
  }

  void _getRelatedResources(String path,String remark) {
    print("========>"+path + "/" + remark);
    ModuleApi().search1(path, "", remark, 0, 100).then((res) {
      setState(() {
        resources.clear();
        resources.addAll(res.data.list);
      });
    });
  }

  void getClasses() {
    ClassApi().classList().then((res) {
      if (res.code == 200) {
        setState(() {
          clList.clear();
          for (Class c in res.data) {
            ClassEntity entity = new ClassEntity(c.classname, c.classid);
            clList.add(entity);
          }

          if (clList.length > 0) {
            ClassEntity entity = clList[0];
            entity.isCheck = true;
            //请求学生列表
            ClassApi().studentList(entity.id).then((res) {
              if (res.code == 200) {
                List<StudentEntity> ss = [];
                ss.add(StudentEntity("全部", 0, true));
                for (Student s in res.data) {
                  StudentEntity e = new StudentEntity(s.name, s.uid, false);
                  ss.add(e);
                }
                class_student_map[entity.id] = ss;
                setState(() {
                  stuList = ss;
                });
              }
            });
          }
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    width = MediaQuery.of(context).size.width;
    var height = MediaQuery.of(context).size.height;
    bool isTeacher = (SPUtils.getRole() == "teacher");
    double item_space = 26;
    return Scaffold(
        appBar: AppBar(
            backgroundColor: Colors.white,
            brightness: Brightness.light,
            toolbarHeight: getPortraitSHeight(40),
            leading: IconButton(
                alignment: Alignment.centerLeft,
                icon: Image.asset(
                  "assets/images/icon_back_black.png",
                  width: getPortraitSWidth(11),
                  height: getPortraitSHeight(18),
                ),
                onPressed: () {
                  Navigator.of(context).pop();
                })),
        backgroundColor: Colors.white,
        body: SafeArea(
          child: Stack(
            children: [
              Positioned(
                child: _playHeaderCol(isTeacher),
                top: 0,
                width: width,
              ),
              if (resources.length > 0)
                Positioned(
                  child: _widget_playlist(),
                  top: getPortraitSHeight(290),
                  width: width,
                  height: height - getPortraitSHeight(350),
                ),
            ],
          ),
        ));
  }

  Widget _playHeaderCol(bool isTeacher) {
    return Container(
      height: getPortraitSHeight(290),
      alignment: Alignment.centerLeft,
      child: Column(
        children: [
          _playHeader(),
          SizedBox(
            height: 10,
          ),
          Row(
            children: [
              SizedBox(
                width: 10,
              ),
              Text(
                currentResource.title,
                style: TextStyle(fontSize: setSp(13), color: text_black),
              ),
            ],
          ),
          Padding(
            padding: EdgeInsets.only(left: 10, right: 10),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                Expanded(
                    child: Text(
                  curVideo != null ? "主讲人:${curVideo.author}" : "",
                  style: TextStyle(fontSize: setSp(11), color: class_tab_gray),
                )),
                InkWell(
                  child: Column(children: [
                    Image.asset(
                      "assets/images/icon_fivorite.png",
                      width: 20,
                      height: 16,
                    ),
                    Text(
                      "收藏",
                      style: TextStyle(fontSize: 11, color: class_tab_gray),
                    )
                  ]),
                  onTap: () {
                    if (isTeacher) {
                      showFavoriteBottomModel();
                    } else {
                      startFavorite();
                    }
                  },
                ),
                SizedBox(
                  width: 10,
                ),
                if (isTeacher)
                  InkWell(
                    child: Column(children: [
                      Image.asset(
                        "assets/images/icon_video_share.png",
                        width: 20,
                        height: 16,
                      ),
                      Text(
                        "投送",
                        style: TextStyle(fontSize: 11, color: class_tab_gray),
                      )
                    ]),
                    onTap: () {
                      showBottomModel();
                    },
                  )
              ],
            ),
          ),
        ],
      ),
    );
  }

  bool showPlayer = true;

  Widget _playHeader() {
    return Stack(
      alignment: Alignment.center,
      children: [
        defaultUrl.length > 0
            ? FijkView(
                player: player,
                height: getPortraitSHeight(220),
                width: SizeConfig.screenWidth,
                color: Colors.white,
                fit: FijkFit.cover,
              )
            : SizedBox(
                height: getPortraitSHeight(220),
                child: Container(
                  color: Colors.black,
                ),
              ),
        Offstage(
            offstage: !showPlayer,
            child: IconButton(
                icon: Icon(
                  Icons.play_circle_outline,
                  color: Colors.transparent,
                  size: 50,
                ),
                onPressed: () {
                  if (player.isPlayable()) {
                    player.start();
                    setState(() {
                      showPlayer = false;
                    });
                  }
                }))
      ],
    );
  }

  Widget _widget_playlist() {
    return ListView.builder(
        padding: const EdgeInsets.all(3),
        itemCount: resources.length,
        itemBuilder: (BuildContext context, int index) {
          //创建子widget
          var resource = resources[index];
          return ListItemVideoPlay(
              title: resource.title,
              detail: video_info_map[index],
              url: resource.url,
              width: width,
              height: getPortraitSHeight(115),
              onTap: () {
                getVideoDetail(resource);
              });
        });
  }

  final FijkPlayer player = FijkPlayer();
  String defaultUrl = '';

  void configPlayer() {
    if (defaultUrl != null && defaultUrl.length > 0) {
      player.reset().then((value) {
        player.setDataSource(defaultUrl, autoPlay: true, showCover: false);
      });

    } else {
      //
      //player.reset();
    }
  }

  Widget buildRoundText(
      String text, Function press, Color color, Color bgColor) {
    return InkWell(
      onTap: press,
      child: Container(
        decoration: BoxDecoration(
            color: bgColor,
            borderRadius: BorderRadius.all(Radius.circular(25))),
        padding: EdgeInsets.symmetric(vertical: 10, horizontal: 40),
        child: Text(
          text,
          style: TextStyle(color: color, fontSize: 16),
        ),
      ),
    );
  }

  void startShare() {
    if (clList.isEmpty || stuList.isEmpty) {
      ToastUtils.error("获取班级或学生信息错误");
      return;
    }

    int classId = -1;
    for (ClassEntity c in clList) {
      if (c.isCheck) {
        classId = c.id;
        break;
      }
    }

    if (classId == -1) {
      ToastUtils.error("请选择班级和学生");
      return;
    }

    List<String> members = [];
    for (StudentEntity s in stuList) {
      if (!s.isAll && s.isCheck) {
        members.add(s.id.toString());
      }
    }
    if (members.isEmpty) {
      ToastUtils.error("请选择班级和学生");
      return;
    }

    Resource resource = currentResource;

    ShareBody shareBody = new ShareBody(
        resid: resource.id,
        type: resource.type,
        url: resource.url,
        title: resource.title,
        uids: members);
    ResourceApi().share(shareBody).then((res) {
      if (res.code == 200) {
        ToastUtils.success(res.msg);
      } else {
        ToastUtils.error(res.msg);
      }
    });
  }

  void showFavoriteBottomModel() {
    showModalBottomSheet(
        context: context,
        isScrollControlled: false,
        backgroundColor: Colors.white,
        shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.only(
                topLeft: Radius.circular(15), topRight: Radius.circular(15))),
        builder: (BuildContext context) {
          return StatefulBuilder(
              builder: (BuildContext context, StateSetter setState) {
            return _buildFavoriteBottom();
          });
        });
  }

  void startFavorite() {
    Resource resource = currentResource;
    FavoriteReqBody body = new FavoriteReqBody(
        resid: resource.id,
        type: resource.type,
        url: resource.url,
        title: resource.title,
        path: "defalut");
    ResourceApi().favorite(body).then((res) {
      if (res.code == 200) {
        ToastUtils.success(res.msg);
      } else {
        ToastUtils.error(res.msg);
      }
    });
  }

  Widget _buildFavoriteBottom() {
    return SizedBox(
        height: getPortraitSHeight(150.5),
        child: Column(
          children: [
            SizedBox(
              height: getPortraitSHeight(14),
            ),
            Row(
              children: [
                Expanded(
                    child: ColorFiltered(
                  colorFilter: ColorFilter.mode(
                    Colors.white,
                    BlendMode.saturation,
                  ),
                  child: getFavoriteItem(
                      "assets/images/icon_my_material.png", "我的素材", () {
                    LogUtil.d("我的素材 click");
                  }),
                )),
                Expanded(
                    child: ColorFiltered(
                  colorFilter: ColorFilter.mode(
                    Colors.white,
                    BlendMode.saturation,
                  ),
                  child: getFavoriteItem(
                      "assets/images/icon_school_material.png", "校园素材", () {
                    LogUtil.d("校园素材 click");
                    return;
                    Navigator.of(context).pop();
                    Navigator.of(context)
                        .push(MaterialPageRoute(builder: (context) {
                      return ChooseFolderPage(
                        resource: currentResource,
                      );
                    }));
                  }),
                )),
                Expanded(
                    child: getFavoriteItem(
                        "assets/images/icon_my_lesson_prepare.png", "我的备课", () {
                  LogUtil.d("我的备课 click");
                  Navigator.of(context).pop();
                  startFavorite();
                }))
              ],
            ),
            SizedBox(
              height: getPortraitSHeight(13.5),
            ),
            Divider(
              height: getPortraitSHeight(2),
              thickness: getPortraitSHeight(2),
              color: bg_divider,
            ),
            InkWell(
                child: SizedBox(
                  width: SizeConfig.screenWidth,
                  height: getPortraitSHeight(52),
                  child: Center(
                      child: Text(
                    "取消",
                    style: TextStyle(
                        color: text_black_confirm, fontSize: setSp(18)),
                  )),
                ),
                onTap: () {
                  Navigator.of(context).pop();
                })
          ],
        ));
  }

  Widget getFavoriteItem(String url, String title, Function onTab) {
    return InkWell(
        onTap: onTab,
        child: Column(
          children: [
            Image.asset(
              url,
              width: getPortraitSWidth(48),
              height: getPortraitSHeight(48),
            ),
            SizedBox(
              height: getPortraitSHeight(2),
            ),
            Text(
              title,
              style: TextStyle(fontSize: setSp(13), color: text_black),
            )
          ],
        ));
  }

  void showBottomModel() {
    showModalBottomSheet(
        context: context,
        isScrollControlled: false,
        backgroundColor: Colors.white,
        shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.only(
                topLeft: Radius.circular(15), topRight: Radius.circular(15))),
        builder: (BuildContext context) {
          return StatefulBuilder(
              builder: (BuildContext context, StateSetter setState) {
            return _buildBottomContainer(setState);
          });
        });
  }

  Widget _buildClassItem(int index, Function setState) {
    ClassEntity entity = clList[index];
    return Padding(
        padding: EdgeInsets.only(
          left: 10,
        ),
        child: Row(mainAxisAlignment: MainAxisAlignment.start, children: [
          RoundCheckBox(
              value: entity.isCheck,
              isRadio: true,
              onChanged: (bool val) {
                LogUtil.d("is Check $index $val");
                if (clList[index].isCheck) // radio效果，选中的时候再点击，
                {
                  setState(() {
                    clList[index].isCheck = true;
                  });

                  return;
                }
                if (val) {
                  setState(() {
                    for (int i = 0; i < clList.length; i++) {
                      bool check = i == index ? true : false;
                      clList[i].isCheck = check;
                    }
                  });
                } else {
                  setState(() {
                    clList[index].isCheck = val;
                  });
                }

                //如果学生列表存在
                if (class_student_map.containsKey(entity.id)) {
                  setState(() {
                    stuList = class_student_map[entity.id];
                  });
                } else {
                  //请求学生列表
                  ClassApi().studentList(entity.id).then((res) {
                    if (res.code == 200) {
                      List<StudentEntity> ss = [];
                      ss.add(StudentEntity("全部", 0, true));
                      for (Student s in res.data) {
                        StudentEntity e =
                            new StudentEntity(s.name, s.uid, false);
                        ss.add(e);
                      }
                      class_student_map[entity.id] = ss;
                      setState(() {
                        stuList = ss;
                      });
                    }
                  });
                }
              }),
          Text(entity.name)
        ]));
  }

  Widget _buildStuItem(int index, Function setState) {
    return Padding(
        padding: EdgeInsets.only(
          left: 10,
        ),
        child: Row(mainAxisAlignment: MainAxisAlignment.start, children: [
          RoundCheckBox(
              value: stuList[index].isCheck,
              onChanged: (bool val) {
                LogUtil.d("is Check $index $val");
                if (index == 0) {
                  for (int i = 0; i < stuList.length; i++) {
                    setState(() {
                      stuList[i].isCheck = val;
                    });
                  }
                } else {
                  setState(() {
                    stuList[index].isCheck = val;
                  });
                }
              }),
          Text(stuList[index].name)
        ]));
  }

  Widget _buildBottomContainer(Function setState) {
    return Container(
      height: 400, //对话框高度就是此高度
      child: Stack(
        children: [
          Positioned(
              bottom: 52,
              width: width,
              height: 300,
              child: Row(
                children: [
                  Expanded(
                      child: ListView.builder(
                          itemCount: clList.length,
                          itemBuilder: (BuildContext context, int index) {
                            return _buildClassItem(index, setState);
                          })),
                  VerticalDivider(
                    width: 2,
                    color: Colors.blueGrey,
                  ),
                  Expanded(
                      child: ListView.builder(
                          itemCount: stuList.length,
                          itemBuilder: (BuildContext context, int index) {
                            return _buildStuItem(index, setState);
                          })),
                ],
              )),
          Positioned(
              bottom: 50,
              width: width,
              child: Divider(
                color: Colors.grey,
                height: 1,
              )),
          Positioned(
            bottom: 0,
            height: 50,
            width: width,
            child: InkWell(
                onTap: () {
                  //todo: 分享
                  Navigator.of(context).pop();
                  startShare();
                },
                child: Center(
                  child: Text("确定"),
                )),
          ),
        ],
      ),
    );
  }

  @override
  void dispose() {
    // videoPlayerController.dispose();
    // chewieController.dispose();
    player.release();
    super.dispose();
  }
}
